/*
** fork_pty.c for  in /home/jousse_f//workspace/SysUnix/script
** 
** Made by florian jousseau
** Login   <jousse_f@epitech.net>
** 
** Started on  Wed Feb 22 12:12:35 2012 florian jousseau
** Last update Fri Feb 24 12:03:43 2012 florian jousseau
*/

#include "my_script.h"

static	void	data_standard(t_script *life)
{
  int	ret;

  ret = read(0, life->input, sizeof(life->input));
  if (ret > 0)
    xwrite(life->fdmaster, life->input, ret);
  else
    {
      life->stop = 1;
      end_call(life);
    }
}

static	void	data_master(t_script *life)
{
  int	ret;

  ret = read(life->fdmaster, life->input, sizeof(life->input));
  if (ret > 0)
    {
      xwrite(1, life->input, ret);
      xwrite(life->fd_file, life->input, ret);
    }
  else
    {
      life->stop = 1;
      end_call(life);
    }
}

static	void	pty_master(t_script *life)
{
  xclose(life->fdslave);
  first_call(life);
  while (life->stop == 0)
    {
      FD_ZERO(&life->fd_check);
      FD_SET(0, &life->fd_check);
      FD_SET(life->fdmaster, &life->fd_check);
      xselect(life->fdmaster + 1, &life->fd_check, NULL, NULL, NULL);
      if (FD_ISSET(0, &life->fd_check))
	data_standard(life);
      if (FD_ISSET(life->fdmaster, &life->fd_check))
	data_master(life);
    }
}

static	void	pty_slave(t_script *life)
{
  xclose(life->fdmaster);
  xtcsetattr(life->fdslave, TCSANOW, &life->orig_term);
  xsetsid();
  ioctl(life->fdslave, TIOCSCTTY, 0);
  xdup2(life->fdslave, 0);
  xdup2(life->fdslave, 1);
  xdup2(life->fdslave, 2);
  xclose(life->fdslave);
  life->shell = xgetenv("SHELL");
  execlp(life->shell, life->shell, NULL);
}

void	pty_fork(t_script *life)
{
  life->pid = fork();

  if (life->pid)
    pty_master(life);
  else
    pty_slave(life);
}
